<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="编码" prop="productId">
            <el-input v-model="ruleForm.productId" placeholder="请输入编码"/>
        </el-form-item>

        <el-form-item label="名称" prop="productName">
            <el-input v-model="ruleForm.productName" placeholder="请输入名称"/>
        </el-form-item>

        <el-form-item label="类别" prop="categoryName">
            <el-select v-model="ruleForm.categoryName" placeholder="请选择类别">
                <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.categoryName"
                    :value="item.categoryName" />
            </el-select>
        </el-form-item>

        <el-form-item label="价格" prop="price">
            <el-input v-model="ruleForm.price" placeholder="请输入价格"/>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            <el-button @click="cancelForm(ruleFormRef)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, toRaw } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
// 表单数据接口
interface RuleForm {
    productId: number | null
    productName: string
    categoryName:string
    price: number | null
}
// 表单属性size
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    productId: null,
    productName: '',
    categoryName: '',
    price: null
})

//表单校验规则
const rules = reactive<FormRules<RuleForm>>({
    productId: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
    productName: [{ required: true, message: '名称不能为空', trigger: 'change' }],
    categoryName: [{ required: true, message: '类别不能为空', trigger: 'change' }],
})

/** 提交表单 */
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const form = toRaw(ruleForm)
            ElMessage.success(JSON.stringify(form))
        } else {
            console.log('error submit!', fields)
        }
    })
}

/** 重置表单 */
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

/** 取消表单 */
const cancelForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()

}

// 静态指定select的options数据,数组类型
const categoryList = [
    {
        categoryId: 1,
        categoryName: '文具'
    },
    {
        categoryId: 2,
        categoryName: '日用品'
    }
]
</script>
